<template>
  <div class="comp-super-kline">
    <div id="tv_chart_container"></div>
  </div>
</template>

<script type="text/babel">
export default {
  components: {},
  data() {
    return {
      timeType: "5m",
      widget: null,
      interval: "15",
      datafeedObj: null,
      chartType: ""
    };
  },
  props: {
    symbol: {
      type: String,
      default: "USDT_BTC"
    },
    height: {
      default: 600
    }
  },
  created() {},

  mounted() {
    this.createTradingView();
  },
  methods: {
    createTradingView() {
      let that = this;
      this.chartType == "";
      function getParameterByName(name) {
        // name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        // var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        //     results = regex.exec(location.pathname);
        // return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        let langArr = window.location.pathname.split("/"),
          lang = "cn";
        switch (langArr[1]) {
          case "cn":
            lang = "zh";
            break;
          case "hk":
            lang = "zh_TW";
            break;
          case "es":
            lang = "es";
            break;
          default:
            lang = "en";
        }
        return lang;
      }

      //            TradingView.onready(function()
      //            {
      //                 if(!that.datafeedObj){
      that.datafeedObj = new Datafeeds.UDFCompatibleDatafeed(
        "https://demo_feed.tradingview.com"
      );
      // }
      var udf_datafeed = that.datafeedObj;
      var maPrecision =
        that.symbol.split("_")[0] === "USC" ||
        that.symbol.split("_")[0] === "USDT"
          ? 2
          : 8;
      that.widget = new TradingView.widget({
        width: "100%",
        height: that.height - 16,
        symbol: that.symbol,
        interval: that.interval,
        container_id: "tv_chart_container",
        datafeed: udf_datafeed,
        library_path: "/third/charting_library/",
        locale: getParameterByName("lang") || "cn",
        drawings_access: {
          type: "black",
          tools: [{ name: "Regression Trend" }]
        },
        disabled_features: [
          "volume_force_overlay",
          "use_localstorage_for_settings",
          "header_symbol_search",
          "header_resolutions",
          "header_interval_dialog_button",
          "header_compare",
          "header_screenshot",
          "header_saveload",
          "timeframes_toolbar"
        ],
        enabled_features: [
          "side_toolbar_in_fullscreen_mode"
          //                        "keep_left_toolbar_visible_on_small_screens"
        ],
        charts_storage_url: "http://saveload.tradingview.com",
        charts_storage_api_version: "1.1",
        client_id: "tradingview.com",
        user_id: "public_user_id",
        overrides: {
          "symbolWatermarkProperties.color": "rgba(0,0,0,0)",
          "paneProperties.legendProperties.showLegend": false,
          "paneProperties.background": "#212121",
          "paneProperties.vertGridProperties.color": "#343535",
          "paneProperties.horzGridProperties.color": "#343535",

          "mainSeriesProperties.candleStyle.upColor": "#ff4622",
          "mainSeriesProperties.candleStyle.downColor": "#17a21d",
          "mainSeriesProperties.candleStyle.drawBorder": false,
          "mainSeriesProperties.candleStyle.wickUpColor": "#ff4622",
          "mainSeriesProperties.candleStyle.wickDownColor": "#17a21d",
          "mainSeriesProperties.candleStyle.borderUpColor": "#ff4622",
          "mainSeriesProperties.candleStyle.borderDownColor": "#17a21d",
          "mainSeriesProperties.priceLineWidth": 2,
          "paneProperties.topMargin": 1,

          "scalesProperties.lineColor": "#555555",
          "scalesProperties.textColor": "#666666",
          "scalesProperties.backgroundColor": "#212121",
          "scalesProperties.rightMargin": 200,
          "scalesProperties.showSeriesPrevCloseValue": true,
          volumePaneSize: "medium" //large/medium/small/tiny
        },
        studies_overrides: {
          "volume.volume.color.0": "rgba(23,162,29,.5)",
          "volume.volume.color.1": "rgba(255,70,34,.5)",
          "Moving Average.precision": maPrecision
        },
        timezone: "Asia/Shanghai",
        debug: false,
        toolbar_bg: "#212121"
      }).onChartReady(function() {
        //默认隐藏左侧导航按钮
        this.chart().executeActionById("drawingToolbarAction");

        //移动平均线
        this.chart().createStudy("Moving Average", false, false, [5], null, {
          "Plot.color": "#ffffff",
          "Plot.linewidth": 2
        });
        this.chart().createStudy("Moving Average", false, false, [10], null, {
          "Plot.color": "yellow",
          "Plot.linewidth": 2
        });
        this.chart().createStudy("Moving Average", false, false, [30], null, {
          "Plot.color": "rgba(255, 0, 255, 0.65)",
          "Plot.linewidth": 2
        });

        //创建时间选择按钮 tab-active
        let resolutions = [
          {
            key: "line",
            val: "Line"
          },
          {
            key: "1",
            val: "1min"
          },
          {
            key: "5",
            val: "5min"
          },
          {
            key: "15",
            val: "15min"
          },
          {
            key: "30",
            val: "30min"
          },
          {
            key: "60",
            val: "1hour"
          },
          {
            key: "D",
            val: "1day"
          }
        ];

        let classNm;
        resolutions.forEach(item => {
          if (item.key === that.interval) {
            //默认15分钟线
            classNm = "header-group-chart-tab tab-active";
          } else {
            classNm = "header-group-chart-tab";
          }

          this.createButton()
            .addClass(classNm)
            .on("click", event => {
              //设置图标样式 line/candles
              if (item.val === "Line") {
                if (that.chartType == "") {
                  this.chart().setChartType(2);
                  that.chartType = "line";
                } else {
                  this.chart().setChartType(1);
                  that.chartType = "";
                }
                return;
              }

              //设置时间区间
              // this.chart().setResolution(item.key);
              that.interval = item.key;
              if (that.datafeedObj.interval) {
                clearInterval(that.datafeedObj.interval);
              }
              this.remove();

              setTimeout(() => {
                console.log("重新渲染TradingView");
                that.createTradingView();
              }, 100);
              $(event.target)
                .parent()
                .siblings()
                .children()
                .removeClass("tab-active");
              $(event.target).addClass("tab-active");
            })
            .append($("<span>" + item.val + "</span>"));
        });

        //创建深度图、蜡烛图、趋势图切换按钮
        this.createButton({ align: "right" })
          .addClass("header-group-chart-tab tab-active")
          .append($("<span>" + that.$t("candlestick") + "</span>"));

        this.createButton({ align: "right" })
          .addClass("header-group-chart-tab")
          .on("click", () => {
            parent.window.document.getElementById("tab-timeshare").click();
          })
          .append($("<span>" + that.$t("priceChart") + "</span>"));

        this.createButton({ align: "right" })
          .addClass("header-group-chart-tab")
          .on("click", () => {
            parent.window.document.getElementById("tab-depth").click();
          })
          .append($("<span>" + that.$t("depthChart") + "</span>"));
      });
      //            });
    }
  }
};
</script>

<style lang="sass" rel="stylesheet/scss">
    .comp-super-kline{
        padding: 0 40px 8px 12px;
    }
</style>
